package cn.bitkit.mybatis;

import cn.bitkit.base.exception.BusinessAssert;
import cn.bitkit.mybatis.entity.EntityClass;
import cn.bitkit.base.util.ReflectUtil;
import cn.bitkit.base.util.StringUtil;

import java.util.stream.Collectors;

/**
 * @author changbo
 */
public class SqlCommonHandler {

    public static String getWhereId(EntityClass entityClass) {
        return getWhereId(entityClass, "");
    }

    public static String getWhereId(EntityClass entityClass, String path) {
        String idField = entityClass.getId().getField();
        if(StringUtil.hasValue(path)){
            idField = path + "." + idField;
        }
        return entityClass.getId().getColumn() + " = #{" + idField + "}";
    }

    public static String updateNonNull(EntityClass entityClass, Object param) {
        return entityClass.getFieldList().stream()
                .filter(e -> ReflectUtil.getValue(param, e.getField()) != null)
                .map(e -> e.getColumn()+" = #{entity."+e.getField()+"}")
                .collect(Collectors.joining(",\n"));
    }

    public static String updateFieldGroup(EntityClass entityClass, Object param, Object group) {
        BusinessAssert.isNotNull(group, "group is null");
        String groupClass = (String) group;
        return entityClass.getFieldList().stream()
                .filter(e -> e.getGroupList().contains(group))
                .map(e -> e.getColumn()+" = #{entity."+e.getField()+"}")
                .collect(Collectors.joining(",\n"));
    }

    public static void checkSql(String sql){
        if(StringUtil.isEmpty(sql)){
            return;
        }
        boolean risk = sql.indexOf(';') >= 0;
        BusinessAssert.isTrue(risk, "sql risk reject:"+sql);
    }

}
